#region Imported Namespaces
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Net;
using System.Collections;
using SSRS;
using System.IO;
#endregion

/// <summary>
/// All the SQL report host pages will use this page to request the report using the reporting web service
/// </summary>
namespace PHSRAG.Insight21
{
    public class SQLRequest
    {
        static string imagePath = "";
        static ArrayList imageFiles = new ArrayList();
        public SQLRequest()
        {
            //
            // TODO: Add constructor logic here
            //
        }

        static ParameterValue[] GetParametersCollection(Hashtable tbl)
        {
            ParameterValue[] oInputPrms = new ParameterValue[tbl.Count];

            int i = 0;
            foreach (string key in tbl.Keys)
            {
                ParameterValue p = new ParameterValue();
                p.Name = key;
                p.Value = (string)tbl[key];
                oInputPrms[i] = p;

                i++;
            }

            return oInputPrms;
        }

        public static void FetchAndDisplayReport(string format, string RptName, Hashtable tbl)
        {
            ParameterValue[] InputParams = GetParametersCollection(tbl);
            FetchAndDisplayReport(format, RptName, InputParams);
        }


        /*This method will fetch the data and write it to the browser
         * The method can be called from the SQL Report Host pages
         */
        public static void FetchAndDisplayReport(string format, string RptName, ParameterValue[] InputParams)
        {
            try
            {
                SSRS.ReportingService oRS = new ReportingService();
                //ReportingService oRS = new ReportingService();

                //oRS.Credentials = new System.Net.NetworkCredential("ys985", "fun2work", "hornet");
                NetworkCredential oCred = new NetworkCredential(
                    Utility.Settings.GetKeyValue("Rpt.UserId", "pn073"),
                    Utility.Settings.GetKeyValue("Rpt.Password", "Insight214"),
                    //Utility.Settings.GetKeyValue("Rpt.Domain", "hornet"));
                    Utility.Settings.GetKeyValue("Rpt.Domain", "partners"));

                oRS.Credentials = oCred;
                oRS.Timeout = 300000;
                imagePath = "Images";
                
                string sHttp ="http://";
                if(HttpContext.Current.Request.IsSecureConnection)
                {
                    sHttp = "https://";
                }
                string imageUrl = sHttp + HttpContext.Current.Request.ServerVariables["HTTP_HOST"] + HttpContext.Current.Request.ApplicationPath + "/" + imagePath + "/";
                    
                string histID = null;
                string deviceInfo = "<DeviceInfo><StreamRoot>" + imageUrl + "</StreamRoot></DeviceInfo>";
                string encoding, mimetype;
                ParameterValue[] oOutParams;
                Warning[] oWarnings;
                string[] streamids;
                byte[] image;
                string imageType = null;

                string TargetReportFolder = Utility.Settings.GetKeyValue("Rpt.TargetReportFolder", @"/insight/frank/");
                byte[] data = oRS.Render(TargetReportFolder + RptName, format, histID, deviceInfo, InputParams,
                    null, null, out encoding, out mimetype, out oOutParams, out oWarnings, out streamids);

                //System.Text.Encoding enc = System.Text.Encoding.ASCII;
                //string myString = enc.GetString(data );

                byte[] htmlReportData = oRS.Render(TargetReportFolder + RptName, "html4.0", histID, null, InputParams,
                    null, null, out encoding, out mimetype, out oOutParams, out oWarnings, out streamids);

                // For each image stream returned by the call to render,
                // render the stream and save it to the application root
                foreach (string streamID in streamids)
                {
                    image = oRS.RenderStream(TargetReportFolder + RptName, "HTML4.0", streamID,
                       null, null, null, out imageType, out imageType);

                    imageType = imageType.Replace("image/", ".");
                    string imageFile = AppDomain.CurrentDomain.GetData("APPBASE") + imagePath + "\\" + streamID + imageType;

                    if (!File.Exists(imageFile))
                    {
                        FileStream stream =  File.OpenWrite(imageFile);
                        imageFiles.Add(imageFile);
                        stream.Write(image, 0, image.Length);
                        stream.Close();
                    }
                }


                HttpContext.Current.Response.Buffer = true;
                HttpContext.Current.Response.AddHeader("Content-Length", data.Length.ToString());
                HttpContext.Current.Response.AddHeader("Expires", "0");
                HttpContext.Current.Response.AddHeader("Pragma", "cache");
                HttpContext.Current.Response.AddHeader("Cache-Control", "private");

                //Set the output stream to the correct content type (PDF).
                if (format == "PDF")
                {
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename= PDFReport.pdf");
                    HttpContext.Current.Response.ContentType = "application/pdf";

                }
                else
                {
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=ExcelReport.xls");
                    HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";

                }

                HttpContext.Current.Response.BinaryWrite(data);

                //Flushing the Response to display the serialized data
                //to the client browser.
                HttpContext.Current.Response.Flush();
            }
            catch (Exception e) { throw e; }
            finally
            { 
                if (imageFiles != null)
                {
                    foreach (string file in imageFiles)
                    {
                        if (File.Exists(file))
                        {
                            System.Threading.Thread.Sleep(5000);
                            File.Delete(file);
                        }

                    }
                }
            }
        }
    }
}
